package com.swu.education.service;

import bitoflife.chatterbean.aiml.A;
import com.swu.education.entity.CourseConnUser;
import com.swu.education.entity.DialogTime;
import com.swu.education.entity.Progress;
import com.swu.education.entity.User;
import com.swu.education.repository.CourseConnUserRepository;
import com.swu.education.repository.DialogRepository;
import com.swu.education.repository.ProgressRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by nana on 2018/3/26.
 */
@Service
public class DialogService {
  @Autowired
  CourseConnUserRepository courseConnUserRepository;

  @Autowired
  ProgressRepository progressRepository;

  @Autowired
  DialogRepository dialogRepository;

  public List<CourseConnUser> removeAllStuDialogByCourseId(int courseId){
    List<CourseConnUser> courseConnUsers = courseConnUserRepository.findAllByCourseId(courseId);
    List userIdList = new ArrayList();
    for(int i=0;i<courseConnUsers.size();i++){
      userIdList.add(courseConnUsers.get(i).getUserId());
    }
    return userIdList;
  }

  public int getStudentProgress(int userId,int activityId){
    try {
      Progress progress = progressRepository.findProgressByUserIdAndActivityId(userId,activityId);
      return progress.getProgressIndex();
    }catch (Exception e){
      return 0;
    }
  }

  public void setStudentProgress(int userId,int activityId,int progressIndex){
    try {
      Progress progress = progressRepository.findProgressByUserIdAndActivityId(userId,activityId);
      progress.setProgressIndex(progressIndex);
      progressRepository.save(progress);
    }catch (Exception e){
      Progress progress = new Progress();
      progress.setActivityId(activityId);
      progress.setUserId(userId);
      progress.setProgressIndex(progressIndex);
      progressRepository.save(progress);
    }
  }

  public void setDialogStart(int userId,int activityId,String startTime){
    try {
      DialogTime dialogTime= dialogRepository.findDialogTimeByUserIdAndActivityId(userId,activityId);
      if(dialogTime == null){
        dialogTime = new DialogTime();
        dialogTime.setUserId(userId);
        dialogTime.setActivityId(activityId);
        dialogTime.setStartTime(startTime);
        dialogRepository.save(dialogTime);
      }
      System.out.println(dialogTime);
    }catch (Exception e){
      System.out.println("do not exist dialogTime ");
    }
  }

  public void setDialogEnd(int userId,int activityId,String endTime){
    DialogTime dialogTime = dialogRepository.findDialogTimeByUserIdAndActivityId(userId,activityId);
    dialogTime.setEndTime(endTime);
    dialogRepository.save(dialogTime);
  }
}
